package com.unitymarvel.harmonyos.projects.findme.common;

import ohos.app.Context;
import ohos.data.DatabaseHelper;
import ohos.data.rdb.RdbOpenCallback;
import ohos.data.rdb.RdbStore;
import ohos.data.rdb.StoreConfig;
import ohos.data.resultset.ResultSet;

import java.util.ArrayList;
import java.util.List;
///////////////////////////////////////////////////
// 项目的详细实现过程：https://ke.qq.com/course/3677276?tuin=a22a65ce
// 关注微信公众号和B站，获取更多鸿蒙学习资源
// 微信公众号：极客起源
// B站：https://space.bilibili.com/477001733
//
// 作者:李宁（蒙娜丽宁）
//
// 版本: 1.0
// Copyright (C), 2001-2022, 李宁
// 程序被版权法保护
//
///////////////////////////////////////////////////

public class DataService {
    private Context context;
    private RdbStore store;   // 数据库对象

    public DataService(Context context) {
        this.context = context;
        StoreConfig config = StoreConfig.newDefaultConfig("game.sqlite");

        // 初始化数据库
        RdbOpenCallback callback = new RdbOpenCallback() {
            @Override
            public void onCreate(RdbStore store) {
                // 创建t_records表
                store.executeSql("create table if not exists t_records(id integer primary key autoincrement, user varchar(30),score int, time datetime default(datetime('now','localtime')))");

            }

            @Override
            public void onUpgrade(RdbStore rdbStore, int oldVersion, int newVersion) {

            }
        };
        DatabaseHelper helper = new DatabaseHelper(context);
        store = helper.getRdbStore(config, 1,callback,null);
    }

    // 保存游戏记录
    public void writeGameRecord(String user, int score) {
        String insertSQL = "insert into t_records(user, score) values(?,?);";
        store.executeSql(insertSQL, new Object[]{user, score});
    }

    // 获取游戏记录
    public List<GameRecord> getGameRecords() {
        ArrayList<GameRecord> result = new ArrayList<>();
        String selectSQL = "select user,score,time from t_records order by score desc, time, user";
        ResultSet resultSet = store.querySql(selectSQL, null);
        while(resultSet.goToNextRow()) {
            GameRecord gameRecord = new GameRecord();
            gameRecord.user = resultSet.getString(0);
            gameRecord.score = resultSet.getInt(1);
            gameRecord.time = resultSet.getString(2);
            result.add(gameRecord);
        }
        return result;

    }

}
